package com.example.myviewpager;

import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import java.util.List;

public class MyPagerAdapter extends PagerAdapter {

    private List<View> views;

    public MyPagerAdapter(List<View> views) {
        this.views = views;
    }

    /**
     * 将给定位置的View添加至ViewGroup容器中，并创建显示出来
     * 返回一个代表新增页面的Object(key)，通常都是直接返回view本身即可
     * @param container The containing View in which the page will be shown.
     * @param position The page position to be instantiated.
     * @return
     */
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = views.get(position);
        container.addView(view, 0);
        return view;
    }

    /**
     * 返回ViewPager中View的个数
     * @return
     */
    @Override
    public int getCount() {
        return views.size();
    }

    /**
     * 判断instantiateItem 返回的View对象是否与方法参数中的对象相等
     * @param view Page View to check for association with <code>object</code>
     * @param object Object to check for association with <code>view</code>
     * @return
     */
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
//        super.destroyItem(container, position, object);
        container.removeView(views.get(position));
    }
}
